package cn.bytecollege.admin.filter;

import cn.bytecollege.common.constant.Resource;
import com.google.code.kaptcha.Constants;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebFilter(filterName = "AdminLoginFilter",servletNames = "AdminLoginController")
public class AdminLoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        String msg = null;
        HttpServletRequest req = (HttpServletRequest) request;
        String method = req.getMethod();
        if (method.equalsIgnoreCase("post")){
            //接收用户名、密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String validCode = request.getParameter("validCode");
            Pattern usernamePattern = Pattern.compile("\\w{5,12}");
            Matcher usernameMather = usernamePattern.matcher(username);
            if (!usernameMather.matches()) {
                //用户名报错
                msg = "用户名是5-12位，只能包含数字、字母、下划线";
                request.setAttribute("msg", msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION + "/admin/login.jsp").forward(request, response);
                return;
            }
            //密码报错
            Pattern passwordPattern = Pattern.compile("((\\d)|[a-z]|[A-Z]){6,12}");
            Matcher passwordMatcher = passwordPattern.matcher(password);
            if (!passwordMatcher.matches()) {
                msg = "密码长度为6-12为的数字或者大小写字母";
                request.setAttribute("msg", msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION + "/admin/login.jsp").forward(request, response);
                return;
            }
            HttpSession session = req.getSession();
            String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
            //验证码错误或者验证码为空
            if (validCode == null || !validCode.equals(code) || validCode.equals("")) {
                msg = "验证码错误";
                request.setAttribute("msg", msg);
                request.getRequestDispatcher(Resource.PAGE_LOCATION + "/admin/login.jsp").forward(request, response);
                return;
            }
            chain.doFilter(request, response);
        }else{
            chain.doFilter(request, response);
        }
    }

}